<?php

App::import('Controller', 'Buildings');
App::import('Model', 'Building');

class ExpendituresController extends AppController {

    var $name = 'Expenditures';

    function index() {
 //           $this->Expenditure->recursive = 0;
//	    $permit  = $this->Session->read('permit_build');                                               
//	if ( $permit!= null ){
          //  $data = null;
          //  $new  = null;
         //   foreach ($permit as $key => $value) {
             //   $this->paginate = array(
            //                 'conditions' => array( 'Expenditure.building_id' => $value )
            //             );  
          //      $data[$key]  = $this->paginate();
	//		}
          //  foreach ( $data as $key1 => $value1)
	//		{   
	//			if ($value1!=null)
	//			{
	//				if ( isset($value1[1]) && (isset($value1[2])) ){
	//					$new[] = $value1[0];
	//					$new[] = $value1[1];
	//					$new[] = $value1[2];
	//				}else{
	//					$new[] = $value1[0];
	//				}
	//			}
		//	}  
	  if( $this->Session->read('grupo') == 'menubuiladmin' )
		{
			$this->set('builadmin', true);
		}else{
			$this->set('builadmin', false);
		}
	//		
	//		$this->set('expenditures', $new);
	//
	//	}else{
       //       $this->Session->setFlash(__('You have nothing assigned', true));
       //       $this->redirect(array('controller' => 'users', 'action' => 'welcome'));
     //   }  
   $this->Expenditure->recursive = 0;
        $this->set('expenditures', $this->paginate());

    }

    function view($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid expenditure', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->set('expenditure', $this->Expenditure->read(null, $id));
    }

    function add() {
         //$building = new Building;
	//	$building_data = $building->find('first', array('conditions' => array('Building.building_id' => $this->data['Expenditure']['building_id'])));
	//	var_dump($building->getExpenseLiquidationType($building_data['Building']));
//var_dump($building_data);FORECAST
//die();
        if (!empty($this->data)) {
            $this->Expenditure->create();
            $this->data['Expenditure']['payment_date'] = null;
            $this->data['Expenditure']['payment_method'] = null;
            $this->data['Expenditure']['invoice_number'] = null;
            if ($this->Expenditure->save($this->data)) {
		//agrego que cuando se carga un gasto, se carge la distribución de gastos por tipo de propiedad para dicho gasto. 
		//Le redirijo a la pagina. No se me ocurre otra forma. Miguel!
                $building = new Building;
		$building_data = $building->find('first', array('conditions' => array('Building.building_id' => $this->data['Expenditure']['building_id'])));
		if($building->getExpenseLiquidationType($building_data['Building'])=='FORECAST'){
		    $this->Session->setFlash(__('The expenditure has been saved. Now you have to create the expenditure distribution.', true));
		    $this->redirect(array('controller' => 'expenditureDistributions', 'action' => 'add'));
		 }else
		 {
		    $this->Session->setFlash(__('The expenditure has been saved', true));
		    $this->redirect(array('action' => 'index'));
		 }
		
            } else {
                $this->Session->setFlash(__('The expenditure could not be saved. Please, try again.', true));
            }
        }
        $buildings = $this->Expenditure->Building->find('list');
        $expenditureTypes = $this->Expenditure->ExpenditureType->find('list');
        $expenditureBuildingExpenditureTypes = array('empty' => 'Select', $this->Expenditure->ExpenditureBuildingExpenditureType->find('list',
                    array('conditions' => array('ExpenditureBuildingExpenditureType.lookup_type' => 'BUILDING_EXPENDITURE_TYPE'))));
        $this->set(compact('buildings', 'expenditureTypes', 'expenditureBuildingExpenditureTypes'));
    }

    function edit($id = null) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid expenditure', true));
            $this->redirect(array('action' => 'index'));
        }
        if (!empty($this->data)) {
            if ($this->Expenditure->save($this->data)) {
                $this->Session->setFlash(__('The expenditure has been saved', true));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The expenditure could not be saved. Please, try again.', true));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Expenditure->read(null, $id);
        }
        $buildings = $this->Expenditure->Building->find('list');
        $expenditureTypes = $this->Expenditure->ExpenditureType->find('list');
        $expenditureBuildingExpenditureTypes = $this->Expenditure->ExpenditureBuildingExpenditureType->find('list',
                        array('conditions' => array('ExpenditureBuildingExpenditureType.lookup_type' => 'BUILDING_EXPENDITURE_TYPE')));
        $expenditurePaymentMethods = $this->Expenditure->ExpenditurePaymentMethod->find('list',
                        array('conditions' => array('ExpenditurePaymentMethod.lookup_type' => 'PAYMENT_METHOD')));
        $this->set(compact('buildings', 'expenditureTypes', 'expenditureBuildingExpenditureTypes', 'expenditurePaymentMethods'));

        // Seteo los campos de acuerdo a su perfil
        $status = $this->readonly($id);
    }

    function readonly($id) {
        $status = 'enabled';
        $status_conso = 'enabled';
        $data = ($this->Session->read('Auth'));
        switch ($data['User']['group_id']) {
            case 2:
                $status_conso = 'disabled';
                break;
            case 4:
                $this->data = $this->Expenditure->read(null, $id);
                if ($this->data['Expenditure']['payment_date'] != null) {
                    $status = 'disabled';
                    $status_conso = 'disabled';
                }
                break;
        }
        $this->set('status', $status);
        $this->set('status_conso', $status_conso);
    }

    function consolidate($id) {
        if (!$id && empty($this->data)) {
            $this->Session->setFlash(__('Invalid expenditure', true));
            $this->redirect(array('action' => 'index'));
        }
        // Verifico que el tenga suficiente saldo en el fondo del edificio
        if (!empty($this->data)) {
            $expen = $this->Expenditure->read(null, $id);
            $build = new Building;
            $build_id = $expen["Expenditure"]["building_id"];
            $build_data = $build->read(null, $build_id);
            if ($expen["Expenditure"]["amount"] <= $build_data["Building"]["regular_fund"]) {
                $this->Expenditure->saveField('payment_date', $this->data["Expenditure"]["payment_date"]);
                $this->Expenditure->saveField('payment_method', $this->data["Expenditure"]["payment_method"]);
                $this->Expenditure->saveField('invoice_number', $this->data["Expenditure"]["invoice_number"]);
                $this->Session->setFlash(__('The consolidate has been saved', true));
                $newTotal = $build_data["Building"]["regular_fund"] - $expen["Expenditure"]["amount"];
                $build->saveField('regular_fund', $newTotal);
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('Insufficient fund, try again', true));
                $this->redirect(array('action' => 'index'));
            }
        }
        if (empty($this->data)) {
            $this->data = $this->Expenditure->read(null, $id);
        }
        $buildings = $this->Expenditure->Building->find('list');
        $expenditureTypes = $this->Expenditure->ExpenditureType->find('list');
        $expenditureBuildingExpenditureTypes = $this->Expenditure->ExpenditureBuildingExpenditureType->find('list',
                        array('conditions' => array('ExpenditureBuildingExpenditureType.lookup_type' => 'BUILDING_EXPENDITURE_TYPE')));
        $expenditurePaymentMethods = $this->Expenditure->ExpenditurePaymentMethod->find('list',
                        array('conditions' => array('ExpenditurePaymentMethod.lookup_type' => 'PAYMENT_METHOD')));
        $this->set(compact('buildings', 'expenditureTypes', 'expenditureBuildingExpenditureTypes', 'expenditurePaymentMethods'));

        // Seteo los campos de acuerdo a su perfil
        $this->set('status', 'disabled');
        $this->set('status_conso', 'enabled');
    }

    function delete($id = null) {
        if (!$id) {
            $this->Session->setFlash(__('Invalid id for expenditure', true));
            $this->redirect(array('action' => 'index'));
        }
        if (empty($this->data)) {
            $this->data = $this->Expenditure->read(null, $id);
        }
        if ($this->data['Expenditure']['payment_date'] <= date('Y-m-d')) {
            $this->Session->setFlash(__('Expenditure can\'t be deleted after the payment date is gone', true));
            $this->redirect(array('action' => 'index'));
        }
        if ($this->Expenditure->delete($id)) {
            $this->Session->setFlash(__('Expenditure deleted', true));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Expenditure was not deleted', true));
        $this->redirect(array('action' => 'index'));
    }

    function show_field() {
        if (!empty($this->data['Expenditure']['building_expenditure_type'])) {
            $buildingExpenditureType = $this->data['Expenditure']['building_expenditure_type'];

            if ($buildingExpenditureType == '4') // FORECAST.
            {
                $this->render('show_forecast');
            } 
            else if ($buildingExpenditureType == '3') // REAL 
            {
                $expenditurePaymentMethods = $this->Expenditure->ExpenditurePaymentMethod->find('list',
                                array('conditions' => array('ExpenditurePaymentMethod.lookup_type' => 'PAYMENT_METHOD')));
                $this->set(compact('expenditurePaymentMethods'));
                $this->render('show_real');
            } else {
                $this->render('add');
            }
        }
    }

}

?>
